package com.zero.minio.server.controller;

import com.google.common.collect.Maps;
import com.zero.minio.server.model.FileDTO;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Item;
import io.minio.messages.Part;
import io.minio.messages.Upload;
import jdk.nashorn.internal.ir.IfNode;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Path;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zero
 */
@RestController
@RequestMapping("upload")
@Log4j2
@CrossOrigin(origins = "*" )
public class UploadRest extends MinioClient{


    private static Map<String,FileDTO> filesUUID = Maps.newHashMap();
    private static Map<String,FileDTO> filesMD5 = Maps.newHashMap();

    private static boolean FileUploaded;

    private static final Long maxPartSize = 1024 * 1024 * 1024 * 5L;

    private static final Long MaxMultipartPutObjectSize = 1024 * 1024 * 1024 * 1024 * 5L;

    private static final String BASE = "OSS";

    private static final String URL = "http://172.20.3.19:9000/minio/upload/oss/";

    protected UploadRest() {
        super(MinioClient.builder()
                .endpoint("http://172.20.3.19:9000")
                .credentials("test", "test@osskey/pwd")
                .build());
    }


    @PostMapping
    public ResponseEntity<String> upload(HttpServletRequest request,MultipartFile[] files){
        log.info("======={}",files.length);
        return ResponseEntity.ok("ok");
    }

    @GetMapping("index")
    public ResponseEntity index(){
        log.info("======={}","index");
        return ResponseEntity.ok("index");
    }


    @SneakyThrows
    @GetMapping("get_chunks/{md5}")
    public ResponseEntity<FileDTO> getChunks(@PathVariable String md5){
        FileDTO fileChunk = filesMD5.get(md5);
        String uuid = null,uploadID = null, chunks = null;
        Boolean uploaded;
        if (fileChunk == null ) {
            return ResponseEntity.ok(null);
        }else{
            uuid = fileChunk.getUuid();
            uploaded = fileChunk.getUploaded();
            uploadID = fileChunk.getUploadID();

            //判断是否存在对象
            Iterable<Result<Item>> list = this.listObjects(ListObjectsArgs.builder().bucket(BASE).prefix(uuid).recursive(false).build());
            //如果为空
            if (list.iterator().hasNext()){
                uploaded = true;
                fileChunk.setUploaded(true);
                filesMD5.put(md5,fileChunk);
                filesMD5.put(uuid,fileChunk);
            }else{
                uploaded = false;
                fileChunk.setUploaded(false);
                filesMD5.put(md5,fileChunk);
                filesMD5.put(uuid,fileChunk);
                ListPartsResponse parts = this.listParts(BASE,null,uuid,null,null,uploadID,null,null);
                if (parts.result().partList().size() > 0){
                    for (Part part : parts.result().partList()) {

                    }
                }
            }
        }
        FileDTO rs = FileDTO.builder().uuid(uuid).uploaded(uploaded).uploadID(uploadID).chunks(chunks).build();

        return ResponseEntity.ok(null);

    }


    @SneakyThrows
    @PostMapping("new_multipart")
    public ResponseEntity<FileDTO> NewMultipart(@RequestBody FileDTO file){
        if (file.getTotalChunks() > maxPartSize || file.getTotalChunks() <=0){
            return ResponseEntity.badRequest().build();
        }
        if (file.getSize() > MaxMultipartPutObjectSize || file.getSize() < 0){
            return ResponseEntity.badRequest().build();
        }
        CreateMultipartUploadResponse response = this.createMultipartUpload(BASE,null,file.getUuid(),null,null);
        file.setUploadID(response.result().uploadId());
        this.createMultipartUpload("","","",null,null);
        return ResponseEntity.ok(null);
    }
}
